package user;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.fitso.model.bean.User;
import com.fitso.model.service.user.UserService;
import com.thoughtworks.selenium.Selenium;
import common.MultiBrowserTest;
import common.SpringFactory;

/**
 * Exercises the creation of a new user account
 * 
 * @author timothystorm
 */
public class CreateAccount extends MultiBrowserTest {
	public CreateAccount(Selenium selenium) throws Exception {
		super(selenium);
	}

	private UserService _userService;
	private static final String FIRST_NAME = "FirstName";
	private static final String LAST_NAME = "LastName";
	private static final String EMAIL = "FirstNameLastName@fitso.com";
	private static final String PASS = "Super$3cret";

	@Before
	public void setUp() throws Exception {
		_userService = (UserService) SpringFactory.getBean("UserService");
	}

	@After
	public void tearDown() {
		super.tearDown();
		
		User user = _userService.fetch(EMAIL, PASS);
		
		if(user != null){
			_userService.delete(user);
		}
	}

	@Test
	public void test_create_account() throws Exception {
		_selenium.open("/");
		_selenium.click("link=Create Account");
		_selenium.waitForPageToLoad("30000");
		_selenium.type("firstName", FIRST_NAME);
		_selenium.type("lastName", LAST_NAME);
		_selenium.type("email", EMAIL);
		_selenium.type("password", PASS);
		_selenium.click("//input[@value='Create']");
		_selenium.waitForPageToLoad("30000");

		// verify the user was logged in and being greeted
		assertTrue(_selenium.isTextPresent(String.format("Welcome %s %s", FIRST_NAME, LAST_NAME)));
		
		
		// sign out
		_selenium.click("link=Sign Out");
		_selenium.waitForPageToLoad("30000");

		// verify that the user is redirected to the login page
		assertThat("Fitso - Fitness Specialized", equalTo(_selenium.getTitle()));
	}
	
	@Test
	public void test_create_account_missing_fields() throws Exception {
		_selenium.open("/");
		_selenium.click("link=Create Account");
		_selenium.waitForPageToLoad("30000");
		_selenium.click("//input[@value='Create']");
		_selenium.waitForPageToLoad("30000");
		
		// verify error messages are showing
		assertTrue(_selenium.isTextPresent(String.format("First name is required")));
		assertTrue(_selenium.isTextPresent(String.format("Last name is required")));
		assertTrue(_selenium.isTextPresent(String.format("Email is required")));
		assertTrue(_selenium.isTextPresent(String.format("Password is required")));
	}
}
